package eval.gui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

import eval.utilities.configuration.ExperimentConfiguration;

/**
 * Writes a jfree chart as a PNG file in the file system
 * */
public class PlotIOSerializer {

	private static ExperimentConfiguration configuration = ExperimentConfiguration
			.getSingleton();

	private static int plotId = 0;
	private static final int lenght = 800;
	private static final int height = 400;

	public static void writeFile(JFreeChart chart, String chartLabels,String resFileName) {
		createDir(resFileName);
		String path = "logs/plots/"+resFileName 
				+ "/" + chartLabels + ".png";
		File f = new File(path);

		try {
			ChartUtilities.saveChartAsPNG(f, chart, lenght, height);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void createDir(String resFileName) {

		File f = new File("logs/plots/" + resFileName+"/");
		if (!f.isDirectory() || !f.exists())
			f.mkdirs();
	}

	public static void writePanelInFile(List<String> messages,String resFileName) {
		createDir(resFileName);
		String path ="logs/plots/" + configuration.optimizationGoal.toString()
				+ "/globalData.txt";

		try {
			Writer out = new OutputStreamWriter(new FileOutputStream(path));
			out.write("\\begin{center}\n");
			out.write("\\begin{tabular}{|c|}\n");
			out.write("\\hline\n");
			
			for (int i = 1; i < messages.size(); i++) {
				String message = messages.get(i);
				message = message.replace("%", "\\%");
				message = message.replace("_", "\\_");
				out.write(message + "   \\\\ ");
				out.write("\\hline \n");
			}

			out.write("\\end{tabular}\n");
			out.write("\\end{center}");
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
